package cn.com.czpb.client.module;

import android.Manifest;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ashokvarma.bottomnavigation.BottomNavigationBar;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechRecognizer;
import com.iflytek.cloud.SpeechUtility;
import com.iflytek.cloud.ui.RecognizerDialog;
import com.iflytek.cloud.ui.RecognizerDialogListener;
import com.iflytek.sunflower.FlowerCollector;
import com.tbruyelle.rxpermissions.RxPermissions;
import com.tencent.bugly.Bugly;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.OnClick;
import cn.com.czpb.client.R;
import cn.com.czpb.client.app.App;
import cn.com.czpb.client.app.ToolBarActivity;

//import cn.com.gxrb.client.model.event.CurrentCityEvent;
import cn.com.czpb.client.model.event.CurrentCityEvent;
import cn.com.czpb.client.model.event.CurrentCityEventForMainAndZiXun;
import cn.com.czpb.client.model.news.AreaChannelBean;
import cn.com.czpb.client.model.news.CityBeanEntity;
import cn.com.czpb.client.module.diantai.Radiofragment;
import cn.com.czpb.client.module.live.LiveFragment;

import cn.com.czpb.client.module.livenew.LiveNewFragment;
import cn.com.czpb.client.module.nanning.NanningFragment;
import cn.com.czpb.client.module.news.ZixunFragment;


import cn.com.czpb.client.module.news.adapter.ChangeCityAdapter;
import cn.com.czpb.client.module.news.dialog.ChangeCityDialog;
import cn.com.czpb.client.module.news.fragment.NewsChannelEditFragment;
import cn.com.czpb.client.module.newsnew.NewsFragment;
import cn.com.czpb.client.module.newspager.NewspagerFragment;
import cn.com.czpb.client.module.notepad.NotePadFragment;
import cn.com.czpb.client.module.todaynet.ToDayNetFragment;
import cn.com.czpb.client.module.video.VideoFragmentMain;
import cn.com.czpb.client.module.video.utils.VideoPlayerHelper;
import cn.com.czpb.client.module.videonew.VideoNewFragment;
import cn.com.czpb.client.net.Factory;
import cn.com.czpb.client.utils.JsonParser;
import cn.com.czpb.client.utils.LogUtils;
import cn.com.czpb.client.utils.PageCtrl;
import cn.com.czpb.client.utils.SPUtil;
import cn.com.czpb.client.utils.TUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Set;

import butterknife.BindView;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;


public class MainActivity extends ToolBarActivity implements BottomNavigationBar.OnTabSelectedListener {

    @BindView(R.id.search_tool_bar)
    ImageView search_tool_bar;
    @BindView(R.id.set_tool_bar)
    ImageView set_tool_bar;
    @BindView(R.id.title_toolbar1)
    TextView title_toolbar1;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.title_toolbar)
    TextView title_toolbar;

    @BindView(R.id.bottom_newsll)
    LinearLayout bottom_newsll;
    @BindView(R.id.bottom_cityll)
    LinearLayout bottom_cityll;
    @BindView(R.id.bottom_cityiv)
    ImageView bottom_cityiv;
    @BindView(R.id.bottom_readingll)
    LinearLayout bottom_readingll;
    @BindView(R.id.bottom_videoll)
    LinearLayout bottom_videoll;

    @BindView(R.id.bottom_video_ll)
    LinearLayout bottom_video_ll;
    @BindView(R.id.bottom_notepad_11)
    LinearLayout bottom_notepad_11;
    @BindView(R.id.bottom_livell)
    LinearLayout bottom_livell;
    @BindView(R.id.bottom_citytv)
    TextView bottom_citytv;
    @BindView(R.id.bottom_citytv2)
    TextView bottom_citytv2;
    @BindView(R.id.frame_fragment)
    FrameLayout frameFragment;

    @BindView(R.id.bottom_cityll2)
    RelativeLayout bottom_cityll2;
    private SPUtil spUtil;
    private int index = 0;
    private List<Fragment> fragments;
    private long mExitTime;

    //    ZixunFragment xinwenFragment;
    NewsFragment newsFragment1;
    ToDayNetFragment toDayNetFragment;
    NotePadFragment notePadFragment;
    LiveNewFragment liveNewFragment;
    VideoNewFragment videoNewFragment;
    Radiofragment radiofragment;

    NanningFragment nanningFragment;
    NewspagerFragment dubaoFragment;
    VideoFragmentMain shipinFragment;
    LiveFragment zhiboFragment;

    public static final String SHOW = "SHOW.IMAGEVIEW";
    public static final String UNSHOW = "UNSHOW.IMAGEVIEW";
    private Set<String> strings;
    private ArrayList<MyOnTouchListener> onTouchListeners = new ArrayList<MyOnTouchListener>(
            10);

    public LocationClient mLocationClient = null;
    private MyLocationListener myListener = new MyLocationListener();
    private Dialog mDialog;
    private GridView gv_dislikelist_id;
    private ChangeCityAdapter adapter;


    private static final String[] PERMISSIONS = new String[]{
//            Manifest.permission.CAMERA,//照相机权限
//            Manifest.permission.WRITE_EXTERNAL_STORAGE,//写入存储的权限;
//            Manifest.permission.READ_PHONE_STATE,//写入存储的权限;
            Manifest.permission.ACCESS_COARSE_LOCATION,//地址
    };

    //BDAbstractLocationListener为7.2版本新增的Abstract类型的监听接口
//原有BDLocationListener接口暂时同步保留。具体介绍请参考后文中的说明
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        LogUtils.e("sss");
        super.onCreate(savedInstanceState);
        initVocie();
        //bugly 全量更新
        Bugly.init(getApplicationContext(), "23fd697d41", false);

//        CrashReport.UserStrategy strategy = new CrashReport.UserStrategy(getApplicationContext());
//...在这里设置strategy的属性，在bugly初始化时传入
//...
//        CrashReport.initCrashReport(getApplicationContext(), "23fd697d41", false);
//
//        strategy.setAppChannel("test");  //设置渠道


        SpeechUtility.createUtility(this, "appid=5ab30ba3");
        // gitchongtu 测试
        spUtil = SPUtil.getInstance();
        title_toolbar.setVisibility(View.GONE);
        App.getInstance().isStartApp = true;
        toolbar.setVisibility(View.GONE);
        search_tool_bar.setVisibility(View.VISIBLE);
        search_tool_bar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                PageCtrl.start2SearchActivity(activity);
            }
        });
        set_tool_bar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                PageCtrl.start2SetActivity(activity);
            }
        });
        //设置返回键消失
        setBackVisiable(false);
        //
        bottom_newsll.setSelected(true);
        strings = new HashSet<>();

        LogUtils.i("city-->" + spu.getCurrentCity());
        strings.add(spu.getCurrentCity());
//        strings.add("18518505305");

        JPushInterface.setTags(this, strings, new TagAliasCallback() {
            @Override
            public void gotResult(int arg0, String arg1, Set<String> arg2) {
                LogUtils.i("arg0-->" + arg0 + " arg1-->" + arg1);
                if (arg2 != null) {
                    for (String s : arg2) {
                        LogUtils.i("arg2->" + s);
                    }
                }
            }
        });
//        JPushInterface.setAlias(this, "18518505305",new TagAliasCallback() {
//            @Override
//            public void gotResult(int arg0, String arg1, Set<String> arg2) {
//                LogUtils.i("arg0-->" + arg0 + " arg1-->" + arg1);
//                if (arg2 != null) {
//                    for (String s : arg2) {
//                        LogUtils.i("arg2->" + s);
//                    }
//                }
//            }
//
//        });

//        checkLocationPermission();


        //注释掉定位;换手动位置
//        getLocation();
//        String oldcity = spu.getCurrentLocation();
//        if("0".equals(oldcity)){
//            ChangeCurrentCity("南宁");
//            showCityDialog();
//        }

//        getCityData();

//        if (spu.getIsFirst()){
//            showPermissionDialog();
//            spu.setIsFirst(false);
//        }


    }

    private void checkLocationPermission() {
        RxPermissions.getInstance(MainActivity.this)
                .request(PERMISSIONS)
                .subscribe(new Action1<Boolean>() {
                    @Override
                    public void call(Boolean granted) {
                        LogUtils.i("granted-->" + granted);
                        if (!granted) {
                            TUtils.toast("拒绝定位权限");
                            String oldcity = spu.getCurrentLocation();
                            if ("0".equals(oldcity)) {
                                ChangeCurrentCity("南宁");
                                showCityDialog();
                            }

                        } else {
                            TUtils.toast("获取定位权限");
                            getLocation();
                        }
                    }
                });


    }

    private void showCityDialog() {

        final ChangeCityDialog changeCityDialog = new ChangeCityDialog(
                activity, R.style.ChangeCitydialog); // 0为修改昵称 1为修改个人签名
        changeCityDialog.show();
        changeCityDialog.setOnChangeCityListener(new ChangeCityDialog.OnChangeCityListener() {
            @Override
            public void onClick(String city) {
                LogUtils.i(city);
                ChangeCurrentCity(city);
                changeCityDialog.dismiss();
            }
        });
    }

    @Override
    public int setMyContentView() {
        return R.layout.activity_main;
    }

    @Override
    public void initView() {
//        bottom_cityiv.setImageResource(R.drawable.bottom_city_big);
        setBottomMode();
//        bottom_cityll.setOrientation(LinearLayout.VERTICAL);
//        bottom_cityll.setGravity(Gravity.CENTER);
        VideoPlayerHelper.init(this);
        hiteToolBarBack();

    }

    private void setBottomMode() {
        if (spu.getIsLarge().equals("1")) {
            setBigStyle();
        } else {
            SetNormalStyle();
        }
    }

    private void setBigStyle() {

    }

    private void SetNormalStyle() {


        bottom_cityll2.setVisibility(View.GONE);
    }

    @Override
    public void initData() {
        createFragments();
    }

    /**
     * 页面设置
     */
    private void createFragments() {
        fragments = new ArrayList<>();

        newsFragment1 = NewsFragment.newInstance();
        notePadFragment = NotePadFragment.newInstance();
        toDayNetFragment = ToDayNetFragment.newInstance();
        liveNewFragment = LiveNewFragment.newInstance();
        videoNewFragment = VideoNewFragment.newInstance();

        radiofragment = Radiofragment.newInstance();
        nanningFragment = NanningFragment.newInstance();
        dubaoFragment = NewspagerFragment.newInstance();
        shipinFragment = VideoFragmentMain.newInstance();

   //////////////////////////
        fragments.add(newsFragment1);
        fragments.add(liveNewFragment);
        fragments.add(videoNewFragment);
        fragments.add(radiofragment);
        fragments.add(dubaoFragment);
        fragments.add(toDayNetFragment);
        fragments.add(notePadFragment);
        setDefaultFragment(index);
    }

    private void setDefaultFragment(int index) {
        fm = getSupportFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        transaction.add(R.id.frame_fragment, fragments.get(index), getTag(index));
        transaction.commit();
    }

    private String getTag(int index) {
        String tag = "news";
        switch (index) {
            case 0:
                tag = "xinwen";

                break;
            case 1:
                tag = "nanning";

                break;
            case 2:
                tag = "dubao";

                break;
            case 3:
                tag = "shipin";

                break;
            case 4:
                tag = "zhibo";
                break;
            case 5:
                tag = "notepad";

                break;
        }
        return tag;
    }

    @OnClick({R.id.bottom_newsll,
            R.id.bottom_cityll,
            R.id.bottom_notepad_11,
            R.id.bottom_cityll2,
            R.id.bottom_readingll,
            R.id.bottom_videoll,
            R.id.bottom_video_ll,
            R.id.bottom_livell})
    public void doclick(View view) {
        initBottonView();

        int position = 0x111;
        switch (view.getId()) {

            case R.id.bottom_newsll:

                bottom_newsll.setSelected(true);
                position = 0;
                break;
            case R.id.bottom_livell:

                bottom_livell.setSelected(true);
                position = 1;
                break;
            case R.id.bottom_video_ll:

                bottom_video_ll.setSelected(true);
                position = 2;
                break;
            case R.id.bottom_cityll:
            case R.id.bottom_cityll2:

                bottom_cityll.setSelected(true);
                bottom_cityll2.setSelected(true);
                position = 3;
                break;
            case R.id.bottom_readingll:

                bottom_readingll.setSelected(true);
                position = 4;
                break;

            case R.id.bottom_videoll:

                bottom_videoll.setSelected(true);
                position = 5;
                break;
            case R.id.bottom_notepad_11:

                bottom_notepad_11.setSelected(true);
                position = 6;
                break;
        }
//        if (position == 0) {
//            search_tool_bar.setVisibility(View.VISIBLE);
//        } else {
//            search_tool_bar.setVisibility(View.GONE);
//        }
//        if (position == 4) {
//            set_tool_bar.setVisibility(View.VISIBLE);
//        } else {
//            set_tool_bar.setVisibility(View.GONE);
//        }
        if (fragments != null) {
            VideoPlayerHelper.getInstance().stop();
            if (position < fragments.size()) {
                LogUtils.e("position" + position);
                index = position;
                fm = getSupportFragmentManager();
                FragmentTransaction transaction = fm.beginTransaction();
                Fragment fragment = fragments.get(position);
                if (!fragment.isAdded()) {
                    transaction.add(R.id.frame_fragment, fragment);
                }
                for (int i = 0; i < fragments.size(); i++) {
                    if (index == i) {
                        transaction.show(fragments.get(i));
                    } else {
                        transaction.hide(fragments.get(i));
                    }
                }
                transaction.commit();
            }
        }
    }

    @Override
    public void onTabSelected(int position) {
        switch (position) {
            case 0:
//                title_toolbar1.setVisibility(View.GONE);
                break;
            case 1:
//                title_toolbar1.setVisibility(View.VISIBLE);
//                title_toolbar1.setText("直播");

                break;
            case 2:
                title_toolbar1.setVisibility(View.VISIBLE);
//                title_toolbar1.setText("南宁");
                break;
            case 3:
//                title_toolbar1.setVisibility(View.VISIBLE);
//                title_toolbar1.setText("读报");
                break;
            case 4:
//                title_toolbar1.setVisibility(View.VISIBLE);
//                title_toolbar1.setText("视频");

                break;
        }
        if (position == 0) {
            search_tool_bar.setVisibility(View.VISIBLE);
        } else {
            search_tool_bar.setVisibility(View.GONE);
        }
        if (position == 4) {
            set_tool_bar.setVisibility(View.VISIBLE);
        } else {
            set_tool_bar.setVisibility(View.GONE);
        }
        if (fragments != null) {
            if (position < fragments.size()) {
                LogUtils.e("position" + position);
                index = position;
                fm = getSupportFragmentManager();
                FragmentTransaction transaction = fm.beginTransaction();
                Fragment fragment = fragments.get(position);
                if (fragment.isAdded()) {
                    transaction.show(fragment);
                } else {
                    transaction.add(R.id.frame_fragment, fragment, getTag(position));
                }
                transaction.commitNowAllowingStateLoss();

            }
        }
    }

    public void addEditChannelFragment() {
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        transaction.setCustomAnimations(R.anim.option_entry_from_bottom, R.anim.option_leave_from_bottom, R.anim.option_entry_from_bottom, R.anim.option_leave_from_bottom);
        transaction.add(R.id.frame_fragment, new NewsChannelEditFragment()).addToBackStack(null);
        transaction.commitAllowingStateLoss();

    }

    @Override
    public void onTabUnselected(int position) {
        if (fragments != null) {
            if (position < fragments.size()) {
                FragmentManager fm = getSupportFragmentManager();
                FragmentTransaction transaction = fm.beginTransaction();
                Fragment fragment = fragments.get(position);
                transaction.hide(fragment);
                transaction.commitAllowingStateLoss();
            }
        }
    }

    @Override
    public void onTabReselected(int position) {

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            // 返回上一个fragment
            FragmentManager fm = getSupportFragmentManager();
            LogUtils.i("count-->" + fm.getBackStackEntryCount());
            if (fm.getBackStackEntryCount() > 0) {
                fm.popBackStack();
                return true;
            }

            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                TUtils.toast("再按一次退出程序");
                mExitTime = System.currentTimeMillis();
            } else {
                this.finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onBackPressed() {
        // 返回上一个fragment
        FragmentManager fm = getSupportFragmentManager();
        LogUtils.i("count-->" + fm.getBackStackEntryCount());
        if (fm.getBackStackEntryCount() > 0) {
            fm.popBackStack();
        }
    }

    @Subscribe
    public void onEventMainThread(CurrentCityEventForMainAndZiXun event) {
        setBottomMode();
        if (spu.getCurrentCountry() != null) {
            strings.clear();
            strings.add(spu.getCurrentCity());
            JPushInterface.setTags(this, strings, new TagAliasCallback() {
                @Override
                public void gotResult(int arg0, String arg1, Set<String> arg2) {
                    LogUtils.i("arg0-->" + arg0 + " arg1-->" + arg1);
                    if (arg2 != null) {
                        for (String s : arg2) {
                            LogUtils.i("arg2->" + s);
                        }
                    }
                }
            });
            bottom_citytv.setText(spu.getCurrentCountry().getChild().get(spu.getCurrentCountryPosition()).getName());
            bottom_citytv2.setText(spu.getCurrentCountry().getChild().get(spu.getCurrentCountryPosition()).getName());
        } else {
            bottom_citytv.setText(spu.getCurrentCity());
            bottom_citytv2.setText(spu.getCurrentCity());
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        for (MyOnTouchListener listener : onTouchListeners) {
            if (listener != null) {
                listener.onTouch(ev);
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    public void registerMyOnTouchListener(MyOnTouchListener myOnTouchListener) {
        onTouchListeners.add(myOnTouchListener);
    }

    public void unregisterMyOnTouchListener(MyOnTouchListener myOnTouchListener) {
        onTouchListeners.remove(myOnTouchListener);
    }

    public interface MyOnTouchListener {
        public boolean onTouch(MotionEvent ev);
    }


    public void getLocation() {
        LogUtils.i("位置-->");
        mLocationClient = new LocationClient(getApplicationContext());
        //声明LocationClient类
        mLocationClient.registerLocationListener(myListener);
        //注册监听函数
        LocationClientOption option = new LocationClientOption();
        option.setIsNeedAddress(true);
        mLocationClient.setLocOption(option);
        mLocationClient.start();
    }


    public class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            //此处的BDLocation为定位结果信息类，通过它的各种get方法可获取定位相关的全部结果
            //以下只列举部分获取地址相关的结果信息
            //更多结果信息获取说明，请参照类参考中BDLocation类中的说明
            String addr = location.getAddrStr();    //获取详细地址信息
            String country = location.getCountry();    //获取国家
            String province = location.getProvince();    //获取省份
            String city = location.getCity();    //获取城市
            String district = location.getDistrict();    //获取区县
            String street = location.getStreet();    //获取街道信息
            checkCity(city);

        }
    }

    private void checkCity(String city0) {
        String city = "";
        LogUtils.i("位置-city->" + city0);
        if (city0.contains("市")) {
            city = city0.substring(0, city0.length() - 1);
        }

        LogUtils.i("位置-city->" + city);
        String oldcity = spu.getCurrentLocation();
        //首次登录 没有保存定位地址
        LogUtils.i("位置-oldcity->" + oldcity);
        if ("0".equals(oldcity)) {
            //如果定位在广西
            if (App.citys.contains(city)) {
                LogUtils.i("位置-1->" + city);
                spu.setCurrentLocation(city);
                ChangeCurrentCity(city);
            }
        } else {
            //新定位城市 和旧城市 一样 什么也不做
            //新城市不同于 就城市
            if (!oldcity.equals(city)) {
                //新城市在广西
                LogUtils.i("位置-2->" + city);
                if (App.citys.contains(city)) {
                    LogUtils.i("位置-3->" + city);
                    spu.setCurrentLocation(city);
                    showCityDialog(city);
                    //新城市不在广西,什么也不做
                } else {

                }
            }
        }
    }

    private void showCityDialog(final String city) {
        /* @setIcon 设置对话框图标
         * @setTitle 设置对话框标题
         * @setMessage 设置对话框消息提示
         * setXXX方法返回Dialog对象，因此可以链式设置属性
         */
        LogUtils.i("位置-4->" + city);
        AlertDialog.Builder normalDialog =
                new AlertDialog.Builder(MainActivity.this, AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
        normalDialog.setTitle("定位到您在  " + city + "\n" +
                "是否切换到当前城市");
        normalDialog.setPositiveButton("取消",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        LogUtils.i("位置-5->" + city);
                    }
                });
        normalDialog.setNegativeButton("切换",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        LogUtils.i("位置-6->" + city);
                        ChangeCurrentCity(city);
                    }
                });
        // 显示
        normalDialog.show();
    }

    private void ChangeCurrentCity(String city) {
        spu.setCurrentLocation(city);
        try {
            LogUtils.i("位置-7->" + city);
            HashMap<String, AreaChannelBean> map = spu.getHashMapData("cityMap", AreaChannelBean.class);
            AreaChannelBean bean = map.get(city);
            LogUtils.i("位置-8->" + bean.getFid());
            spu.setCurrentCity(bean.getName());
            spu.setCurrentCityId(bean.getId());
            spu.setCurrentCounty(null);
            spu.setIsLarge(bean.getIslarge());
            CurrentCityEventForMainAndZiXun event2 = new CurrentCityEventForMainAndZiXun();
            EventBus.getDefault().post(event2);
            CurrentCityEvent event = new CurrentCityEvent();
            event.setCurrentCity(bean.getName());
            event.setCurrentCityId(bean.getId());
            event.setPosition(0);
            EventBus.getDefault().post(event);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    //获取数字报列表
    private void getCityData() {
        Factory.provideHttpService3()
                .getCity()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<CityBeanEntity, Boolean>() {
                    @Override
                    public Boolean call(CityBeanEntity entity) {
                        LogUtils.i("flash--200-->" + entity.code);
                        return "200".equals(entity.code);
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<CityBeanEntity>() {
                               @Override
                               public void call(CityBeanEntity entity) {
                                   if ("0".equals(entity.code)) {
                                       String city = entity.data.getCity();

                                       String oldcity = spu.getCurrentLocation();
                                       if ("0".equals(oldcity)) {
                                           //如果定位在广西
                                           if (App.citys.contains(city)) {
                                               LogUtils.i("位置-1->" + city);
                                               spu.setCurrentLocation(city);
                                               ChangeCurrentCity(city);
                                           }
                                       }
                                   }


                               }
                           }, new Action1<Throwable>() {
                               @Override
                               public void call(Throwable throwable) {
                                   LogUtils.i("flash--200-->失败" + throwable.toString());
                               }
                           }
                );
    }


    //    private void showPermissionDialog() {
//
//        final PermisionDialog permisionDialog = new PermisionDialog(
//                MainActivity.this, R.style.ChangeCitydialog); // 0为修改昵称 1为修改个人签名
//        permisionDialog.show();
//        permisionDialog.setOnClickKnowListener(new PermisionDialog.OnClickKnowListener() {
//            @Override
//            public void onClick() {
//            }
//        });
//    }
// 初始化识别无UI识别对象
// 使用SpeechRecognizer对象，可根据回调消息自定义界面；
// 语音听写对象
    private SpeechRecognizer mIat;
    // 引擎类型
    private String mEngineType = SpeechConstant.TYPE_CLOUD;

    // 语音听写UI
    private RecognizerDialog mIatDialog;

    // 用HashMap存储听写结果
    private HashMap<String, String> mIatResults = new LinkedHashMap<String, String>();

    private String PERMISSION = Manifest.permission.RECORD_AUDIO;

    private void initVocie() {
        mIat = SpeechRecognizer.createRecognizer(activity, mInitListener);
        mIatDialog = new RecognizerDialog(activity, mInitListener);
    }

    ;

    @OnClick(R.id.img_yuyin)
    public void OnClick(View view) {
        RxPermissions.getInstance(activity)
                .request(PERMISSION)
                .subscribe(new Action1<Boolean>() {
                    @Override
                    public void call(Boolean granted) {
                        LogUtils.i("granted-->" + granted);
                        if (!granted) {
                            new android.app.AlertDialog.Builder(activity)
                                    .setTitle("应用缺少录音权限,请授权")
                                    .setPositiveButton("去设置", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            // 帮跳转到该应用的设置界面，让用户手动授权
                                            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                            Uri uri = Uri.fromParts("package", activity.getPackageName(), null);
                                            intent.setData(uri);
                                            startActivity(intent);
                                        }
                                    }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            });

                        } else {
                            startVoice();
                        }
                    }
                });


    }

    /**
     * 听写UI监听器
     */
    private RecognizerDialogListener mRecognizerDialogListener = new RecognizerDialogListener() {
        public void onResult(RecognizerResult results, boolean isLast) {

            printResult(results);

        }

        /**
         * 识别回调错误.
         */
        public void onError(SpeechError error) {

            showTip(error.getPlainDescription(true)
            );
        }

    };

    private void startVoice() {
        // 移动数据分析，收集开始听写事件
        FlowerCollector.onEvent(activity, "iat_recognize");
        mIatResults.clear();
        // 设置参数
        setParam();
        // 显示听写对话框
        mIatDialog.setListener(mRecognizerDialogListener);
        mIatDialog.show();
        Toast.makeText(activity, "请开始说话", Toast.LENGTH_LONG).show();
    }


    private void printResult(RecognizerResult results) {
        String text = JsonParser.parseIatResult(results.getResultString());

        String sn = null;
        // 读取json结果中的sn字段
        try {
            JSONObject resultJson = new JSONObject(results.getResultString());
            sn = resultJson.optString("sn");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        mIatResults.put(sn, text);

        StringBuffer resultBuffer = new StringBuffer();

        for (String key : mIatResults.keySet()) {

            resultBuffer.append(mIatResults.get(key));
        }

        SetSelectBottumView(resultBuffer.toString());
    }

    private void SetSelectBottumView(String content) {
        int position = 0;
        initBottonView();
        if (content.contains("新闻")) {
            bottom_newsll.setSelected(true);
            position = 0;
        } else if (content.contains("直播")) {
            bottom_livell.setSelected(true);
            position = 1;
        } else if (content.contains("点播")) {
            bottom_video_ll.setSelected(true);
            position = 2;
        } else if (content.contains("电台")) {
            bottom_cityll.setSelected(true);
            position = 3;
        } else if (content.contains("读报")) {
            bottom_readingll.setSelected(true);
            position = 4;
        } else if (content.contains("今日")) {
            bottom_videoll.setSelected(true);
            position = 5;
        } else if (content.contains("速记")) {
            bottom_notepad_11.setSelected(true);
            position = 6;
        } else {
            bottom_newsll.setSelected(true);
            position = 0;
        }
        if (fragments != null) {
            VideoPlayerHelper.getInstance().stop();
            if (position < fragments.size()) {
                LogUtils.e("position" + position);
                index = position;
                fm = getSupportFragmentManager();
                FragmentTransaction transaction = fm.beginTransaction();
                Fragment fragment = fragments.get(position);
                if (!fragment.isAdded()) {
                    transaction.add(R.id.frame_fragment, fragment);
                }
                for (int i = 0; i < fragments.size(); i++) {
                    if (index == i) {
                        transaction.show(fragments.get(i));
                    } else {
                        transaction.hide(fragments.get(i));
                    }
                }
                transaction.commit();
            }
        }
    }

    private void initBottonView() {
        bottom_newsll.setSelected(false);
        bottom_cityll.setSelected(false);
        bottom_cityll2.setSelected(false);
        bottom_readingll.setSelected(false);
        bottom_videoll.setSelected(false);
        bottom_video_ll.setSelected(false);
        bottom_livell.setSelected(false);
        bottom_notepad_11.setSelected(false);
    }

    /**
     * 初始化监听器。
     */
    private InitListener mInitListener = new InitListener() {

        @Override
        public void onInit(int code) {
            if (code != ErrorCode.SUCCESS) {
                showTip("初始化失败，错误码：" + code);
            }
        }
    };

    /**
     * 参数设置
     *
     * @return
     */
    public void setParam() {
        // 清空参数
        mIat.setParameter(SpeechConstant.PARAMS, null);

        // 设置听写引擎
        mIat.setParameter(SpeechConstant.ENGINE_TYPE, mEngineType);
        // 设置返回结果格式
        mIat.setParameter(SpeechConstant.RESULT_TYPE, "json");

//        this.mTranslateEnable = mSharedPreferences.getBoolean( this.getString(R.string.pref_key_translate), false );
//        if( mTranslateEnable ){
//            Log.i( TAG, "translate enable" );
//            mIat.setParameter( SpeechConstant.ASR_SCH, "1" );
//            mIat.setParameter( SpeechConstant.ADD_CAP, "translate" );
//            mIat.setParameter( SpeechConstant.TRS_SRC, "its" );
//        }

//        String lag = mSharedPreferences.getString("iat_language_preference",
//                "mandarin");
//        if (lag.equals("en_us")) {
//            // 设置语言
//            mIat.setParameter(SpeechConstant.LANGUAGE, "en_us");
//            mIat.setParameter(SpeechConstant.ACCENT, null);
//
//            if( mTranslateEnable ){
//                mIat.setParameter( SpeechConstant.ORI_LANG, "en" );
//                mIat.setParameter( SpeechConstant.TRANS_LANG, "cn" );
//            }
//        } else {
        // 设置语言
        mIat.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
        // 设置语言区域
        mIat.setParameter(SpeechConstant.ACCENT, "zh_cn");

//            if( mTranslateEnable ){
//                mIat.setParameter( SpeechConstant.ORI_LANG, "cn" );
//                mIat.setParameter( SpeechConstant.TRANS_LANG, "en" );
//            }
//        }

        // 设置语音前端点:静音超时时间，即用户多长时间不说话则当做超时处理
        mIat.setParameter(SpeechConstant.VAD_BOS, "4000");

        // 设置语音后端点:后端点静音检测时间，即用户停止说话多长时间内即认为不再输入， 自动停止录音
        mIat.setParameter(SpeechConstant.VAD_EOS, "1000");

        // 设置标点符号,设置为"0"返回结果无标点,设置为"1"返回结果有标点
        mIat.setParameter(SpeechConstant.ASR_PTT, "0");

        // 设置音频保存路径，保存音频格式支持pcm、wav，设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限
        // 注：AUDIO_FORMAT参数语记需要更新版本才能生效
        mIat.setParameter(SpeechConstant.AUDIO_FORMAT, "wav");
        mIat.setParameter(SpeechConstant.ASR_AUDIO_PATH, Environment.getExternalStorageDirectory() + "/msc/iat.wav");
    }


    private void showTip(final String str) {
        TUtils.toast(str);
    }


}
